package com.fivetalks.filter;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JsonCorsFilter implements Filter {

	public void init(FilterConfig fConfig) throws ServletException {}

	@SuppressWarnings("unchecked")
	public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException {

		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		
		System.out.println("=========================================JsonCorsFilter 필터링 시작================================================");
    	Enumeration e = httpServletRequest.getHeaderNames();
    	while( e.hasMoreElements() ) {
    		String headerName = (String) e.nextElement();
    		System.out.println( headerName + ":" + httpServletRequest.getHeader( headerName ) );
    	}		
		System.out.println("===============================================================================================================");
		
		// 
		if( httpServletRequest.getHeader( "Access-Control-Request-Method" ) != null && "OPTIONS".equals( httpServletRequest.getMethod() ) ) {
			 /* CORS "pre-flight" request */
			 httpServletResponse.addHeader( "Access-Control-Allow-Origin", "*" );
			 httpServletResponse.addHeader( "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE" );
			 httpServletResponse.addHeader( "Access-Control-Allow-Headers", "Content-Type" );
			 httpServletResponse.addHeader( "Access-Control-Max-Age", "1800" ); //30 min
		 }
		
		//
		Map<String, String[]> parms = httpServletRequest.getParameterMap();
		
		if( parms.containsKey( "callback" ) ) {
			
			GenericResponseWrapper responseWrapper = new GenericResponseWrapper( httpServletResponse );
			responseWrapper.setContentType( "text/javascript; charset=UTF-8" );

			chain.doFilter( request, responseWrapper );

			OutputStream out = httpServletResponse.getOutputStream();
			out.write( new String( parms.get( "callback")[0] + "(").getBytes() );
			out.write( responseWrapper.getData() );
			out.write( new String( ");" ).getBytes() );
			out.close();
			
			System.out.println("JSONP WORKS!! - " + new String( parms.get( "callback")[0] + "(" ).getBytes() + responseWrapper.getData() + new String( ");" ).getBytes() );
		
			
		} else {
			httpServletResponse.setHeader( "Access-Control-Allow-Origin", "*" );
			chain.doFilter( request, response );
			//out.write( responseWrapper.getData() );
			//System.out.println( "+" + responseWrapper.getData() + "+" );
		}
		
	}

	public void destroy() {}
}